package com.rogan.rea;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class Handle implements Runnable{
	final SocketChannel channel;
	final SelectionKey sk;
	ByteBuffer input = ByteBuffer.allocate(1024);
	ByteBuffer output = ByteBuffer.allocate(1024);
	static final int READING=0, SENDING=1;
	int state = READING;
	
	public Handle(Selector selector, SocketChannel c) throws IOException {
		channel = c;
		c.configureBlocking(false);
		sk = channel.register(selector, 0);
		sk.attach(this);
		sk.interestOps(SelectionKey.OP_READ);
		selector.wakeup();
	}

	boolean inputIsComplete()
	{
		return false;
	}

	boolean outputIsComplete()
	{
		return false;
	}

	void process()
	{
		return ;
	}

	@Override
	public void run() {
	  try {
		  if(state == READING )
		  {
			  read();
		  }
		  else if (state == SENDING)
		  {
			  send();
		  }
	  } catch (IOException ex){}
		
	}

	void read() throws IOException 
	{
		channel.read(input);
		if (inputIsComplete()) {
			process();
			state = SENDING;
			sk.interestOps(SelectionKey.OP_WRITE);
		}
	}

	void send() throws IOException
	{
		channel.write(output);
		if (outputIsComplete()) {
			sk.cancel();
		}
	}

}
